package javaspaces;

import net.jini.space.JavaSpace;
import net.jini.core.event.RemoteEvent;
import net.jini.core.event.RemoteEventListener;
import net.jini.core.event.UnknownEventException;
import net.jini.export.Exporter;

import net.jini.jeri.BasicILFactory;
import net.jini.jeri.BasicJeriExporter;

import net.jini.jeri.tcp.TcpServerEndpoint;

import java.io.IOException;
import java.io.Serializable;
import java.rmi.MarshalledObject;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Date;

public class NotifiedConsumer implements Serializable, RemoteEventListener {

	private transient RemoteEventListener theStub;

	public Date date;

	NotifiedConsumer() throws RemoteException {
		date = new Date();
		Exporter myDefaultExporter = new BasicJeriExporter(TcpServerEndpoint
				.getInstance(0), new BasicILFactory(), false, true);

		theStub = (RemoteEventListener) myDefaultExporter.export(this);

	}

	public static void main(String args[]) {
		NotifiedConsumer consumer;
		try {
			consumer = new NotifiedConsumer();
			consumer.work();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void work() {
		WorkEntry template = new WorkEntry();
		JavaSpace space = Locator.getSpace();
		try {
			space.notify(template, null, theStub, 60 * 1000, new MarshalledObject(
					this));
			Thread.sleep(60000);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void notify(RemoteEvent event) throws UnknownEventException,
			RemoteException {
		// TODO Auto-generated method stub
		try {
			System.out.println("NOTIFY: " + 
					event.getSequenceNumber()+
					" "+
					(NotifiedConsumer)event.getRegistrationObject().get());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String toString() {
		return "NOTIFIED CONSUMER("+date+")";
	}
}
